package tech.aistar.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Ray
 * @version 1.0
 * @description:本类用来演示:过滤器来处理中文乱码问题[post请求]
 * @date 2019/9/9  19:14
 */
@WebFilter(urlPatterns = "/*",initParams = {@WebInitParam(name = "encoding", value = "utf-8")})
public class EncodingFilter implements Filter {
    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //处理中文请求的乱码
        req.setCharacterEncoding(encoding);

        //直接放行
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}
